package com.thti.mecool.client.model.biz;

import java.util.ArrayList; 
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.database.Cursor;
import com.thti.mecool.client.base.HandlerConstant;
import com.thti.mecool.client.db.DataBase;
import com.thti.mecool.client.model.po.PlanClient;
import com.thti.mecool.client.util.Util;

public class PlanBizImpl {
	
	private DataBase dataBase;

	public PlanBizImpl(Context context) {
		dataBase = new DataBase(context);
	}
	
	public void save(PlanClient planClient){
		String sqlString="insert into plan(userId ,planId,planName,isFlag,isType,planTime,status,denyNotes ,changeNotes,type,createTime) values(?,?,?,?,?,?,?,?,?,?,?)";
		dataBase.execObject(sqlString, new String[]{planClient.getUserId(),planClient.getPlanId(),planClient.getPlanName(),String.valueOf(planClient.getIsFlag()),String.valueOf(planClient.getIsType()),planClient.getPlanTime(),planClient.getStatus(),planClient.getDenyNotes(),planClient.getChangeNotes(),planClient.getType(),String.valueOf(planClient.getCreateTime())});
		dataBase.close();
	}
	
	public void update(PlanClient planClient){
		String sqlString="update plan set planName=? where planId=?";
		dataBase.execObject(sqlString, new String[]{planClient.getPlanName(),planClient.getPlanId()});
		dataBase.close();
	}
	
//	public void deleteByPlanId(String planId){
//		String sqlString="delete from plan  where planId=?";
//		dataBase.execObject(sqlString, new String[]{planId});
//		dataBase.close();
//	}

	public void delete(String planId,boolean flag){
		dataBase.getWritableDatabase().beginTransaction();//开始事务
			try {
				dataBase.getWritableDatabase().execSQL("delete from plan  where planId=?", new String[]{planId});
				dataBase.getWritableDatabase().execSQL("delete from  project where planId=?", new String[]{planId});
				dataBase.getWritableDatabase().execSQL("delete from  task where planId=?", new String[] { planId });
					if(flag){
					    dataBase.getWritableDatabase().execSQL("delete  from taskStep where planId=?", new Object[]{planId});
					}
				dataBase.getWritableDatabase().setTransactionSuccessful();//调用此方法会在执行到endTransaction() 时提交当前事务，如果不调用此方法会回滚事务
			} finally {
				dataBase.getWritableDatabase().endTransaction();//由事务的标志决定是提交事务，还是回滚事务
			}
			dataBase.getWritableDatabase().close(); 
	}
	
	public void deleteProject(String planId,String projectId,String taskId){
		dataBase.getWritableDatabase().beginTransaction();//开始事务
			try {
				dataBase.getWritableDatabase().execSQL("delete from plan  where planId!=?", new String[]{planId});
				dataBase.getWritableDatabase().execSQL("delete from  project where planId!=? AND projectId!=?", new String[]{planId,projectId});
				dataBase.getWritableDatabase().execSQL("delete from  task where planId!=? AND projectId!=? AND taskId !=?", new String[] { planId,projectId,taskId });
				dataBase.getWritableDatabase().setTransactionSuccessful();//调用此方法会在执行到endTransaction() 时提交当前事务，如果不调用此方法会回滚事务
			} finally {
				dataBase.getWritableDatabase().endTransaction();//由事务的标志决定是提交事务，还是回滚事务
			}
			dataBase.getWritableDatabase().close(); 
	}
	
	public int findPlanId(){
		String sqlString="select  * from  plan where isType=0 order by createTime DESC  limit 0,1";
		Cursor cursor=dataBase.queryObject(sqlString, new String[]{});
		int i=0;
		while(cursor.moveToNext()){
		  i=cursor.getInt(cursor.getColumnIndex("id"));
		}
		cursor.close();
		dataBase.close();
		return i;
	} 
	
	public int findPlanCount(int isType,String userId){
		String sqlString="select count(*) id from plan where isType=? and userId=?";
		Cursor cursor=dataBase.queryObject(sqlString, new String[]{String.valueOf(isType),userId});
		int i=0;
		while(cursor.moveToNext()){
		  i=	cursor.getInt(cursor.getColumnIndex("id"));
		}
		cursor.close();
		dataBase.close();
		return i;
	} 
	
 

  public PlanClient findByPlanId(int isType,int  id,String userId){

		String sql="select  * from plan where isType=? and planId=? and  userId=?";
		PlanClient PlanClient=(PlanClient)dataBase.findByObject(PlanClient.class, sql, new String[]{String.valueOf(isType),String.valueOf(id),userId});
		dataBase.close();

		return PlanClient;
	} 
  
  public PlanClient findUploadPlan(int  id,String userId){

		String sql="select  * from plan where  planId=? and  userId=?";
		PlanClient PlanClient=(PlanClient)dataBase.findByObject(PlanClient.class, sql, new String[]{String.valueOf(id),userId});
		dataBase.close();
System.out.println(PlanClient.getPlanId());
		return PlanClient;
	}
  /**
   * 计划管理
   * @param PlanClientTime
   * @return
   */
  public PlanClient findByPlanDate(String PlanClientTime,String  userId){
		String sql="select  * from plan where isType=1 and planTime=? and  userId=?";
		
		PlanClient PlanClient=(PlanClient)dataBase.findByObject(PlanClient.class, sql, new String[]{PlanClientTime,userId});
		dataBase.close();
		return PlanClient;
	} 
	
	@SuppressWarnings("unchecked")
	public List<PlanClient> findAll(){
		// select pro.PlanClientId,p.PlanClientName,p.userId,pro.projectName,t.taskId,t.taskName,t.storeId,t.storeName,t.startTime,t.endTime from PlanClient p,project pro,task t where p.id=pro.PlanClientId AND pro.id=t.projectId
		String sql="select  * from plan where isType=0  order by createTime DESC ";
		List<PlanClient> list=dataBase.findAll(PlanClient.class, sql, new String[]{});
		dataBase.close();
		return list;
		
	}
	
	/**
	 * 判断projrctId是已经存在
	 * @param id
	 * @return
	 */
	public boolean findByPlanId(String  planId,int userId){
		String sqlString="select  * from plan where planId=? AND userId=?";
		Cursor cursor=dataBase.queryObject(sqlString, new String[]{planId,String.valueOf(userId)});
		if(cursor.moveToNext()){
			boolean flag = cursor.getLong(0)>0 ?true:false;
			cursor.close();
			dataBase.close();
			return flag;
		}
		cursor.close();
		dataBase.close();
		return false;
	} 
	
	public boolean findByProjectId(String  planId,String projectId ,int userId){
		String sqlString="select  * from project where planId=? AND projectId=? AND userId=?";
		Cursor cursor=dataBase.queryObject(sqlString, new String[]{planId,projectId,String.valueOf(userId)});
		if(cursor.moveToNext()){
			boolean flag = cursor.getLong(0)>0 ?true:false;
			cursor.close();
			dataBase.close();
			return flag;
		}
		cursor.close();
		dataBase.close();
		return false;
	} 
	public boolean findByTaskId(String  planId,String projectId,String taskId,int userId){
		String sqlString="select  * from task where planId=? AND projectId=? AND taskId=? AND userId=?";
		Cursor cursor=dataBase.queryObject(sqlString, new String[]{planId,projectId,taskId,String.valueOf(userId)});
		if(cursor.moveToNext()){
			boolean flag = cursor.getLong(0)>0 ?true:false;
			cursor.close();
			dataBase.close();
			return flag;
		}
		cursor.close();
		dataBase.close();
		return false;
	} 
	
	
	public void savePlan(List<Map<String,Object[]>> list){
		dataBase.getWritableDatabase().beginTransaction();//开始事务
		if(list!=null && list.size()>0){
			try {
				Util.print("size:   "+list.size());
				for (int i = 0; i < list.size(); i++) {
					if(list.get(i).containsKey(HandlerConstant.PLAN_SQL)){
					//	Util.print(HandlerConstant.PLAN_SQL+":   "+list.get(i).get(HandlerConstant.PLAN_SQL));
						dataBase.getWritableDatabase().execSQL(HandlerConstant.PLAN_SQL,list.get(i).get(HandlerConstant.PLAN_SQL));
					}else if(list.get(i).containsKey(HandlerConstant.PROJECT_SQL)){
					//	Util.print(HandlerConstant.PROJECT_SQL+":   "+list.get(i).get(HandlerConstant.PROJECT_SQL));
						dataBase.getWritableDatabase().execSQL(HandlerConstant.PROJECT_SQL,list.get(i).get(HandlerConstant.PROJECT_SQL));
					}else if(list.get(i).containsKey(HandlerConstant.TASK_SQL)){
						//Util.print(HandlerConstant.TASK_SQL+":   "+list.get(i).get(HandlerConstant.TASK_SQL));
		 				dataBase.getWritableDatabase().execSQL(HandlerConstant.TASK_SQL,list.get(i).get(HandlerConstant.TASK_SQL));
					}else if(list.get(i).containsKey(HandlerConstant.TASK_STEP_SQL)){
						//Util.print(HandlerConstant.TASK_STEP_SQL+":   "+list.get(i).get(HandlerConstant.TASK_STEP_SQL));
						dataBase.getWritableDatabase().execSQL(HandlerConstant.TASK_STEP_SQL,list.get(i).get(HandlerConstant.TASK_STEP_SQL));
					}
				}
				dataBase.getWritableDatabase().setTransactionSuccessful();//调用此方法会在执行到endTransaction() 时提交当前事务，如果不调用此方法会回滚事务
			} finally {
				dataBase.getWritableDatabase().endTransaction();//由事务的标志决定是提交事务，还是回滚事务
			} 
			
		}
		dataBase.getWritableDatabase().close(); 
	}
	
	@SuppressWarnings("unchecked")
	public List<PlanClient> findByType(String date){
		// select pro.PlanClientId,p.PlanClientName,p.userId,pro.projectName,t.taskId,t.taskName,t.storeId,t.storeName,t.startTime,t.endTime from PlanClient p,project pro,task t where p.id=pro.PlanClientId AND pro.id=t.projectId
		String sql="select  * from plan where isType=1 and planTime=? order by type ISNULL";
		List<PlanClient> list=dataBase.findAll(PlanClient.class, sql, new String[]{date});
		dataBase.close();
		return list!=null?list:new ArrayList<PlanClient>();
	}
	/**
	 * 查询变更或退回的计划
	 * @param isType
	 * @param planTime
	 * @return
	 */
	public PlanClient findByType(int isType,String planTime,String userId){
		// select pro.PlanClientId,p.PlanClientName,p.userId,pro.projectName,t.taskId,t.taskName,t.storeId,t.storeName,t.startTime,t.endTime from PlanClient p,project pro,task t where p.id=pro.PlanClientId AND pro.id=t.projectId
		String sql="select  * from plan where isType=? and planTime=? and userId=? order by createTime DESC ";
		PlanClient planClient=(PlanClient)dataBase.findByObject(PlanClient.class, sql, new String[]{String.valueOf(isType),planTime,userId});
		dataBase.close();
		return planClient;
	}
}
